package controllers;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;

import game.Game;
import game.server.SedServiceHandler;
import domain.Map;
import domain.SedRequest;
import domain.SedResponse;
import play.*;
import play.libs.F.Promise;
import play.libs.Json;
import play.libs.WS;
import play.mvc.*;

import util.MapRenderer;
import util.Stat;
import views.html.*;

public class Application extends Controller {

	public static Result index() {

		return ok(index.render("App"));
	}

	/**
	 * 
	 * @return
	 */
	public static Result startGame() {

		Game game = Game.newGame();

		if (game.start()) {
			return ok("Game started");
		} else {
			return badRequest("Game start failed");
		}

	}

	/**
	 * 
	 * @return
	 */
	public static Result map() {

		Map map = new Map();
		map.mapSize = 5;

		MapRenderer renderer = new MapRenderer(map);

		SedRequest sedRequest = new SedRequest();
		sedRequest.hire.add(1);

		//String resp = Json.stringify(Json.toJson(request(sedRequest)));
		String resp = "fake";
		
		return ok(mapView.render(renderer, resp));
	}

	/**
	 * 
	 * @return
	 */
	public static Result stat() {
		
		SedResponse resp = Game.current() == null ? new SedResponse() : Game.current().getLastResponse();		
		resp = resp == null ? new SedResponse()  : resp;
	
		return ok(stats.render(new Stat(resp)));
	}

	public static Result pollStatus() {
		
		if (null != Game.current() && Game.current().turn != 0) {			
			Game.current().requestStatus();
		}
		
		return ok("refreshed");

	}
	
	/**
	 * 
	 * @param sedRequest
	 * @return
	 */
	public static SedResponse request(SedRequest sedRequest) {

		JsonNode jsonNode = Json.toJson(sedRequest);

		String url = getServiceUrl();
		String parameter = Json.stringify(jsonNode);

		try {

			Promise<SedResponse> promise = WS
					.url(url)
					.setHeader(play.mvc.Http.HeaderNames.CONTENT_TYPE,
							"application/json").post(parameter)
					.map(new SedServiceHandler());

			return promise.get();

		} catch (Exception e) {
			return null;
		}

	}

	public static String getServiceUrl() {

		return "http://localhost:3723/sedcup2013/teams/Client1";

	}

}